<?php

namespace System\Loader;

/**
 * 类库别名类
 * 
 * @package Dream
 * @subpackage ClassAlias
 * @namespace System\Loader
 * @author lewis (lewisld@yeah.net)
 */
class ClassAlias
{

    /**
     * 所有类库别名
     * 
     * @static
     *
     * @access protected
     * @var array
     */
    protected static $classList = [];

    /**
     * 注册类库别名
     * 
     * @static
     *
     * @access public
     * @param string|array $alias 类库别名名称，可以是字符串或数组
     * @param string $path 类库别名指向的类
     * @return void 无返回值
     */
    public static function registerClass($alias, $file = '')
    {
        if (is_array($alias)) {
            foreach ($alias as $key => $value) {
                if (NULL != $value) {
                    $key = preg_replace('/\/+/', '.', str_replace('\\', '/', $key));
                    $value = preg_replace('/\/+/', DS, str_replace('\\', '/', $value));
                    $info = pathinfo($value);
                    $path = PathAlias::getPath($info['dirname']);
                    self::$classList[$key] = (string) $path . $info['filename'] . '.php';
                }
            }
            
            return TRUE;
        } else {
            if (NULL != $file) {
                $alias = preg_replace('/\/+/', '.', str_replace('\\', '/', $alias));
                $file = preg_replace('/\/+/', DS, str_replace('\\', '/', $file));
                $info = pathinfo($file);
                $path = PathAlias::getPath($info['dirname']);
                self::$classList[$key] = (string) $path . $info['filename'] . '.php';
                
                return TRUE;
            }
        }
        unset($alias, $file, $key, $value, $info, $path);
        
        return FALSE;
    }

    /**
     * 获取类库别名
     * 
     * @static
     *
     * @access public
     * @param string $alias
     * @return string 别名存在就返回别名指向的类，否则返回原始信息
     */
    public static function getClass($alias)
    {
        $alias = preg_replace('/\/+/', '.', str_replace('\\', '/', $alias));
        if (isset(self::$classList[$alias])) {
            unset($alias);
            
            return self::$classList[$alias];
        }
        unset($alias);
        
        return $alias;
    }

    /**
     * 获取所有类库别名
     * 
     * @static
     *
     * @access public
     * @return array 返回所有类库别名数组
     */
    public static function getAllClass()
    {
        return self::$classList;
    }
}
